const { pool } = require('../config/db');

exports.getAllTargets = async (req, res) => {
    const [rows] = await pool.query('SELECT * FROM redirect_targets');
    return res.json(rows);
};

exports.getTargetById = async (req, res) => {
    const { id } = req.params;
    const [[target]] = await pool.query('SELECT * FROM redirect_targets WHERE id = ?', [id]);
    if (!target) {
        return res.status(404).send('Target not found');
    }
    return res.json(target);
};

exports.searchTargets = async (req, res) => {
    const { resource_id, group_id, target_url } = req.query;
    let query = 'SELECT t.*, r.name as resource_name, g.group_name FROM redirect_targets t ' +
                'LEFT JOIN resources r ON t.resource_id = r.id ' +
                'LEFT JOIN redirect_groups g ON t.group_id = g.id ' +
                'WHERE 1=1';
    const params = [];
    
    if (resource_id) {
        query += ' AND t.resource_id = ?';
        params.push(resource_id);
    }
    
    if (group_id) {
        query += ' AND t.group_id = ?';
        params.push(group_id);
    }
    
    if (target_url) {
        query += ' AND t.target_url LIKE ?';
        params.push(`%${target_url}%`);
    }
    
    const [rows] = await pool.query(query, params);
    return res.json(rows);
};

exports.createTarget = async (req, res) => {
    try {
        const { resource_id, group_id, target_url } = req.body;
        
        // 验证必填字段
        if (!target_url) {
            return res.status(400).send('Target URL is required');
        }
        
        // 验证资源ID是否存在
        if (resource_id) {
            const [[resource]] = await pool.query('SELECT id FROM resources WHERE id = ?', [resource_id]);
            if (!resource) {
                return res.status(404).send('Resource not found');
            }
        }
        
        // 验证组ID是否存在
        if (group_id) {
            const [[group]] = await pool.query('SELECT id FROM redirect_groups WHERE id = ?', [group_id]);
            if (!group) {
                return res.status(404).send('Group not found');
            }
        }
        
        const [result] = await pool.query(
            'INSERT INTO redirect_targets (resource_id, group_id, target_url) VALUES (?, ?, ?)', 
            [resource_id || null, group_id || null, target_url]
        );
        
        return res.status(201).json({
            message: 'Target created successfully',
            id: result.insertId,
            resource_id: resource_id || null,
            group_id: group_id || null,
            target_url
        });
    } catch (error) {
        console.error('Error creating target:', error);
        return res.status(500).send('Failed to create target');
    }
};

exports.updateTarget = async (req, res) => {
    try {
        const { id } = req.params;
        const updates = req.body;
        
        // 验证是否有要更新的字段
        if (Object.keys(updates).length === 0) {
            return res.status(400).send('No fields to update');
        }
        
        // 检查目标是否存在
        const [[existingTarget]] = await pool.query('SELECT * FROM redirect_targets WHERE id = ?', [id]);
        if (!existingTarget) {
            return res.status(404).send('Target not found');
        }
        
        // 验证资源ID是否存在
        if (updates.resource_id !== undefined) {
            if (updates.resource_id) {
                const [[resource]] = await pool.query('SELECT id FROM resources WHERE id = ?', [updates.resource_id]);
                if (!resource) {
                    return res.status(404).send('Resource not found');
                }
            }
        }
        
        // 验证组ID是否存在
        if (updates.group_id !== undefined) {
            if (updates.group_id) {
                const [[group]] = await pool.query('SELECT id FROM redirect_groups WHERE id = ?', [updates.group_id]);
                if (!group) {
                    return res.status(404).send('Group not found');
                }
            }
        }
        
        // 构建动态更新查询
        const fields = [];
        const values = [];
        
        if (updates.resource_id !== undefined) {
            fields.push('resource_id = ?');
            values.push(updates.resource_id || null);
        }
        
        if (updates.group_id !== undefined) {
            fields.push('group_id = ?');
            values.push(updates.group_id || null);
        }
        
        if (updates.target_url !== undefined) {
            if (!updates.target_url) {
                return res.status(400).send('Target URL cannot be empty');
            }
            fields.push('target_url = ?');
            values.push(updates.target_url);
        }
        
        if (fields.length === 0) {
            return res.status(400).send('No valid fields to update');
        }
        
        // 添加ID到参数数组
        values.push(id);
        
        // 执行更新
        await pool.query(
            `UPDATE redirect_targets SET ${fields.join(', ')} WHERE id = ?`, 
            values
        );
        
        // 获取更新后的数据
        const [[updatedTarget]] = await pool.query('SELECT * FROM redirect_targets WHERE id = ?', [id]);
        
        return res.json({
            message: 'Target updated successfully',
            target: updatedTarget
        });
    } catch (error) {
        console.error('Error updating target:', error);
        return res.status(500).send('Failed to update target');
    }
};

exports.deleteTarget = async (req, res) => {
    try {
        const { id } = req.params;
        
        // 检查目标是否存在
        const [[existingTarget]] = await pool.query('SELECT * FROM redirect_targets WHERE id = ?', [id]);
        if (!existingTarget) {
            return res.status(404).send('Target not found');
        }
        
        // 执行删除
        await pool.query('DELETE FROM redirect_targets WHERE id = ?', [id]);
        
        return res.json({
            message: 'Target deleted successfully',
            id: parseInt(id)
        });
    } catch (error) {
        console.error('Error deleting target:', error);
        return res.status(500).send('Failed to delete target');
    }
};

exports.deleteTargetsByResourceId = async (req, res) => {
    try {
        const { rid } = req.params;

        // 检查资源是否存在
        const [[existingResource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [rid]);
        if (!existingResource) {
            return res.status(404).send('Resource not found');
        }

        // 检查是否有依赖关系（例如，是否有targets引用此resource_id）
        const [relatedTargets] = await pool.query('SELECT COUNT(*) as count FROM redirect_targets WHERE resource_id = ?', [rid]);
        if (relatedTargets[0].count > 0) {
            await pool.query('DELETE FROM redirect_targets WHERE resource_id = ?', [rid]);
        }

        // 执行删除
        // await pool.query('DELETE FROM redirect_targets WHERE id = ?', [id]);

        return res.json({
            message: 'All Targets deleted successfully',
            id: parseInt(id)
        });
    } catch (error) {
        console.error('Error deleting target:', error);
        return res.status(500).send('Failed to delete target');
    }
};